package org.hank.compose_yyzs.ui.screen

import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SheetValue
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.annotation.RootNavGraph
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import kotlinx.coroutines.launch
import org.hank.compose_yyzs.R
import org.hank.compose_yyzs.ui.destinations.ProjectScreenDestination
import org.hank.compose_yyzs.ui.destinations.TipsDialogDestination
import org.hank.compose_yyzs.ui.widget.clickNoWave
import org.hank.compose_yyzs.viewmodel.LoginViewEvent
import org.hank.compose_yyzs.viewmodel.LoginViewModel

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2023/5/30 15:28
 *描述: 登录页面
 */
@Composable
fun EditLayoutsInput(loginViewModel: LoginViewModel, modifier: Modifier = Modifier) {
    val account by loginViewModel.userAccount.collectAsState()
    val pass by loginViewModel.userPass.collectAsState()
    var isShowPass by remember { mutableStateOf(false) }
    val focus = LocalFocusManager.current
    Column(
        modifier = modifier
            .padding(top = 12.dp), horizontalAlignment = Alignment.CenterHorizontally
    ) {
        OutlinedTextField(
            value = account,
            onValueChange = { loginViewModel.onAccountChange(it) },
            label = {
                Text(
                    text = stringResource(id = R.string.login_user_hint),
                    style = MaterialTheme.typography.bodyMedium.copy(colorResource(id = R.color.gray_6))
                )
            },
            trailingIcon = {
                if (account.isNotEmpty())
                    Icon(painter = painterResource(id = R.mipmap.ic_account_delete),
                        contentDescription = "",
                        modifier = Modifier.clickable {
                            loginViewModel.onAccountChange("")
                        })
            },
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Number,
                imeAction = ImeAction.Next,
            ),
            keyboardActions = KeyboardActions(onDone = {
                //切换到下一个控件
                focus.moveFocus(focusDirection = FocusDirection.Next)
            }),
            maxLines = 1,
            textStyle = MaterialTheme.typography.bodyMedium,
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight()
                .padding(start = 36.dp, end = 36.dp),
            )

        Spacer(modifier = Modifier.height(16.dp))

        OutlinedTextField(
            value = pass,
            onValueChange = { loginViewModel.onPassChange(it) },
            label = {
                Text(
                    text = stringResource(id = R.string.login_pass_hint),
                    style = MaterialTheme.typography.bodyMedium.copy(colorResource(id = R.color.gray_6))
                )
            },
            trailingIcon = {
                Icon(painter = painterResource(id = if (!isShowPass) R.drawable.icon_eye_disable else R.drawable.icon_eye_show),
                    contentDescription = "",
                    modifier = Modifier
                        .clickable(
                            indication = null,
                            interactionSource = remember { MutableInteractionSource() }) {
                            isShowPass = !isShowPass
                        }
                        .size(22.dp)
                )
            },
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Password,
                imeAction = ImeAction.Done
            ),
            keyboardActions = KeyboardActions(onDone = {
                focus.clearFocus()
            }),
            visualTransformation = if (!isShowPass) PasswordVisualTransformation() else VisualTransformation.None,
            maxLines = 1,
            textStyle = MaterialTheme.typography.bodyMedium,
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight()
                .padding(start = 36.dp, end = 36.dp, top = 16.dp)
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
@RootNavGraph(start = true)
@Destination
fun LoginScreen(navigator: DestinationsNavigator) {
    val viewmodel: LoginViewModel = hiltViewModel()
    var focusManager = LocalFocusManager.current
    var state = rememberModalBottomSheetState()
    var scope = rememberCoroutineScope()
    var softControl = LocalSoftwareKeyboardController.current

    LaunchedEffect(Unit) {
        viewmodel.viewEvents.collect {
            if (it is LoginViewEvent.ErrorMessage) {
                navigator.navigate(TipsDialogDestination(it.message))
            } else if (it is LoginViewEvent.LoginSuccess) {
                navigator.navigate(ProjectScreenDestination.route)
            }
        }
    }

    Surface {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .clickNoWave {
                    focusManager.clearFocus()
                }
        ) {
            Image(
                painter = painterResource(id = R.mipmap.ic_login_title),
                contentDescription = "",
                modifier = Modifier
                    .padding(top = 128.dp)
                    .align(Alignment.TopCenter)
            )
            EditLayoutsInput(loginViewModel = viewmodel, Modifier.align(Alignment.Center))

            Button(
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .fillMaxWidth()
                    .padding(bottom = 64.dp, start = 36.dp, end = 36.dp),
                onClick = {
                    scope.launch {
                        viewmodel.login()
                    }
                    softControl?.hide()
                    focusManager.clearFocus()
                },
                shape = MaterialTheme.shapes.medium
            ) {
                Text(
                    modifier = Modifier.padding(
                        start = 64.dp,
                        end = 64.dp,
                        top = 4.dp,
                        bottom = 4.dp
                    ),
                    text = stringResource(id = R.string.login),
                    style = MaterialTheme.typography.titleMedium
                )
            }

//            if (state.currentValue == SheetValue.Expanded)
//                BottomMerchantDialog(
//                    listItems = viewmodel.merchantInfo.value,
//                    state = state,
//                    navigator = navigator,
//                    onItemClick = {
//                        scope.launch {
//                            state.hide()
//                            viewmodel.setMerchant(it)
//                        }
//                    }
//                ) {
//                    scope.launch {
//                        state.hide()
//                    }
//                }
        }
    }
}